/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.skywalking.oap.server.library.module;

import java.util.*;

/**
 * The <code>ModuleManager</code> takes charge of all {@link ModuleDefine}s in collector.
 *
 * @author wu-sheng, peng-yongsheng
 */
public class ModuleManager implements ModuleDefineHolder {

    private boolean isInPrepareStage = true;
    // Key是Module的名称，Value是相应的ModuleDefine，ModuleDefine就是对Module的抽象
    // 《核心Module对应的名称.png》
    private final Map<String, ModuleDefine> loadedModules = new HashMap<>();

    /**
     * Init the given modules
     *
     * 首先会通过 SPI 的方式加载插件配置文件中定义的 Module 实现类和 ModuleProvider 实现类，
     * 并调用其 prepare() 方法执行一些准备操作，最后创建 BootstrapFlow 开始启动流程。
     */
    public void init(ApplicationConfiguration applicationConfiguration) throws ModuleNotFoundException, ProviderNotFoundException, ServiceNotProvidedException, CycleDependencyException, ModuleConfigException, ModuleStartException {
        // 根据配置拿到所有Module的名称
        String[] moduleNames = applicationConfiguration.moduleList();
        // 通过SPI方式加载ModuleDefine接口和ModuleProvider接口的实现
        ServiceLoader<ModuleDefine> moduleServiceLoader = ServiceLoader.load(ModuleDefine.class);
        ServiceLoader<ModuleProvider> moduleProviderLoader = ServiceLoader.load(ModuleProvider.class);

        LinkedList<String> moduleList = new LinkedList<>(Arrays.asList(moduleNames));
        for (ModuleDefine module : moduleServiceLoader) {
            for (String moduleName : moduleNames) {
                if (moduleName.equals(module.name())) {
                    // 通过SPI可能加载很多ModuleDefine实现以及ModuleProvider实现类，
                    // 但是这里只初始化在配置文件中出现过的Module,并调用其prepare()方法
                    ModuleDefine newInstance;
                    try {
                        newInstance = module.getClass().newInstance();
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new ModuleNotFoundException(e);
                    }
                    // 加载模块的提供者，并执行提供者的准备阶段
                    // 通过 Module 名称在 application.yml 配置文件中查找相应的配置信息
                    // 例如：moduleName = storage，则：
                    //      1、newInstance 为 StorageModule 实例；
                    //      2、从 applicationConfiguration 获取的是 ModuleConfiguration 实例；
                    //      3、ModuleConfiguration 实例中 providers 字段包含的就是：elasticsearch -> ProviderConfiguration 对象。
                    newInstance.prepare(this, applicationConfiguration.getModuleConfiguration(moduleName), moduleProviderLoader);
                    // 记录初始化的ModuleDefine对象
                    loadedModules.put(moduleName, newInstance);
                    moduleList.remove(moduleName);
                }
            }
        }
        // Finish prepare stage
        isInPrepareStage = false;

        if (moduleList.size() > 0) {
            throw new ModuleNotFoundException(moduleList.toString() + " missing.");
        }

        // 初始化BootstrapFlow
        // 内部会对模块的启动进行排序
        BootstrapFlow bootstrapFlow = new BootstrapFlow(loadedModules);

        // 模块的启动阶段。会检查依赖模块是否已经启动。
        // 启动Module
        bootstrapFlow.start(this);
        // 启动流程结束之后会通知相关组件
        // 通知全部 ModuleProvider 实例：全部 Module 已正常启动了，可以对外提供服务了
        bootstrapFlow.notifyAfterCompleted();
    }

    @Override public boolean has(String moduleName) {
        return loadedModules.get(moduleName) != null;
    }

    @Override public ModuleProviderHolder find(String moduleName) throws ModuleNotFoundRuntimeException {
        assertPreparedStage();
        ModuleDefine module = loadedModules.get(moduleName);
        if (module != null)
            return module;
        throw new ModuleNotFoundRuntimeException(moduleName + " missing.");
    }

    private void assertPreparedStage() {
        if (isInPrepareStage) {
            throw new AssertionError("Still in preparing stage.");
        }
    }
}
